/* Task.hpp */

#ifndef TASK_HPP
#define TASK_HPP
#include <iostream>
#include <string>

#include "Init.hpp"
#include "log.hpp"

Init init;
extern Log lg;

class Task
{
public:
  Task() {} // 默认构造

  // 构造函数：初始化所有成员变量
  Task(int sockfd, const std::string &clientip, const uint16_t clientport)
      : sockfd_(sockfd), clientip_(clientip), clientport_(clientport) {}

  // 析构函数（当前为空）
  ~Task() {}

  // 执行任务的主要函数
  void run()
  {
    char buff[4096];
    int n = read(sockfd_, buff, sizeof(buff));
    if (n > 0)
    {
      buff[n] = 0;
      std::cout << "Client key# " << buff << std::endl;
      std::string ret = init.translation(buff);
      n = write(sockfd_, ret.c_str(), ret.size()); // 发回客户端
      // n = write(100, ret.c_str(), ret.size()); // 发回客户端
      if(n<0){
        lg(WARNING,"write error, error message: %s",strerror(errno));
      }
    }
    else if (n == 0)
    {
      lg(INFO, "Client %s:%d quit... ", clientip_.c_str(), clientport_);
    }
    else
    {
      lg(WARNING, "read error , error message: %s", strerror(errno));
    }
    close(sockfd_);
  }

  // 重载()运算符，使对象可以像函数一样被调用
  void operator()() { run(); }

private:
  int sockfd_;
  std::string clientip_;
  uint16_t clientport_;
};

#endif
